package run.siyuan.jdk.漫画算法.栈;

/**
 * @ClassName ArrayStack
 * @Description TODO 数组实现栈的入栈出栈
 * @Author siyuan
 * @Date 2023/4/8 14:25
 */
public class ArrayStack {

    private int[] array;
    private int size;

    public ArrayStack(int capacity) {
        this.array = new int[capacity];
        this.size = 0;
    }

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.pushStack(0);
        stack.pushStack(1);
        stack.pushStack(2);
        stack.pushStack(3);
        stack.pushStack(4);
        stack.show();

        stack.popStack();
        stack.show();
        stack.pushStack(5);
        stack.pushStack(6);
        stack.pushStack(7);
        stack.pushStack(8);
        stack.pushStack(9);
        stack.show();

    }

    /**
     * 入栈
     *
     * @param element 元素
     */
    public void pushStack(int element) {
        if (size == this.array.length) {
            resize();
        }
        this.array[size] = element;
        size++;
    }

    /**
     * 扩容原来的 1.5 倍
     */
    public void resize() {
        int length = this.array.length >> 1;
        length = length + this.array.length;
        int[] array = new int[length];
        for (int i = 0; i < this.array.length; i++) {
            array[i] = this.array[i];
        }
        this.array = array;
    }

    /**
     * 出栈
     */
    public void popStack() {
        int index = size - 1;
        this.array[index] = 0;
        size--;
    }

    /**
     * 打印
     */
    public void show() {
        for (int i = 0; i < size; i++) {
            System.out.printf("%d\t%d\n", i, this.array[i]);
        }
    }
}
